package com.qf.quduba.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.qf.quduba.config.WebSocket;
import com.qf.quduba.service.RechargeService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author 17312
 * @time2020/9/2220:48
 */
@RestController
@RequestMapping("/pay")
public class WxPayController {
    @Resource
    private RechargeService rechargeService;

    @RequestMapping("callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.在回调接口中接收 微信平台 发送的 支付信息
        ServletInputStream is = request.getInputStream();
        byte[] bs = new byte[1024];
        int len = -1;
        StringBuilder builder = new StringBuilder();
        while((len = is.read(bs))!=-1){
            builder.append( new String(bs,0,len) );
        }
        String res = builder.toString();
        Map<String, String> respMap = WXPayUtil.xmlToMap(res);

        //2.从微信回调的数据中获取订单编号
        String rechargeId = respMap.get("out_trade_no");
        String returnCode = respMap.get("return_code");
        // 修改订单表，状态为“已支付”
        int i = rechargeService.updateRecharge(rechargeId);




        //3.将付款状态推送到支付页面
        WebSocket.sendMsg("success",rechargeId);

        //4.响应微信平台（如果不响应，微信平台则将不断调用回调接口）
        PrintWriter out = response.getWriter();
        String reMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        out.println(reMsg);
        out.flush();
        out.close();
    }


}
